import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class UserSenderConnection extends Thread {
	private List<Message> messagesToSend;
	private String nickname;
	private ObjectOutputStream outStream;
	private boolean stopped;
	private Socket socket;

	public UserSenderConnection(ObjectOutputStream outStream) {
		super();
		this.outStream = outStream;
		messagesToSend = new ArrayList<Message>();
		stopped = false;
	}
	
	public UserSenderConnection(Socket s) throws IOException {
		super();
		this.socket = s;
		this.outStream = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
		outStream.flush();
		messagesToSend = new ArrayList<Message>();
		stopped = false;
	}


	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public void addMessageToSend(Message m) {
		synchronized (messagesToSend) {
			messagesToSend.add(m);
			messagesToSend.notify();
		}
	}

	@Override
	public void run() {

		while (outStream != null && !stopped) {
			Message messageToSend;
			synchronized (messagesToSend) {
				while (messagesToSend.isEmpty()) {
					try {
						messagesToSend.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				messageToSend = messagesToSend.remove(0);

			}

			if (messageToSend != null) {
				try {
					outStream.writeObject(messageToSend);
					outStream.flush();
				} catch (IOException e) {
					try {
						outStream.close();
					} catch (IOException e1) {
					}
					stopped = true;
					
				}
			} else {
				try {
					outStream.close();
				} catch (IOException e) {
				}
				stopped = true;
			}
		}

	}

	public void setStopped() {
		try {
			outStream.close();
		} catch (IOException e) {
		}
		stopped = true;
	}
	
	public Socket getSocket(){
		return socket;
	}

}
